package com.example.blog.service;

import com.example.blog.entity.Blog;
import com.example.blog.entity.Type;
import com.example.blog.handler.NotFoundException;
import com.example.blog.respository.BlogRepository;
import com.example.blog.util.MarkdownUtils;
import com.example.blog.util.MyBeanUtils;
import com.example.blog.vo.BlogQuery;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.criteria.*;
import java.util.*;

@Service
public class BlogServiceImpl implements BlogService{
    @Autowired
    private BlogRepository blogRepository;

@Cacheable(cacheNames = "getBlog",unless = "#result==null")
    @Override
    public Blog getBlog(Long id) {
        return blogRepository.getOne(id);
    }
    @Cacheable(cacheNames = "blog",unless = "#result==null")
    @CachePut(cacheNames = "blog",key = "#result.id")
@Transactional
    @Override
    public Blog getAndConvert(Long id) {
        Blog blog = blogRepository.getOne(id);
        if (blog == null) {
            throw new NotFoundException("该博客不存在");
        }
        Blog b = new Blog();
       BeanUtils.copyProperties(blog,b);
        String content = b.getContent();
      b.setContent(MarkdownUtils.markdownToHtmlExtensions(content));
        blogRepository.updateViews(id);//更新views
        return b;
    }

    @Cacheable(cacheNames = "blog",unless = "#result==null")
    @Override
    public Page<Blog> listBlog(Pageable pageable, BlogQuery blog) {

            return blogRepository.findAll(new Specification<Blog>() {
            @Override
            public Predicate toPredicate(Root<Blog> root, CriteriaQuery<?> cq, CriteriaBuilder cb) {
                List<Predicate> predicates = new ArrayList<>();
                if(!"".equals(blog.getTitle())&& blog.getTitle() !=null){
                    predicates.add(cb.like(root.<String>get("title"),"%"+blog.getTitle()+"%"));
                }
                if(blog.getTypeId()!=null){
                    predicates.add(cb.equal(root.<Type>get("type").get("id"), blog.getTypeId()));
                }
                if(blog.isRecommend()){
                    predicates.add(cb.equal(root.<Boolean>get("recommend"),blog.isRecommend()));
                }
                cq .where(predicates.toArray(new Predicate[predicates.size()]));
                return null;
            }
        },pageable);}
    @Cacheable(cacheNames = "blog",unless = "#result==null")
    @Override
    public List<Blog> listBlog() {
        return blogRepository.findAll();
    }
    @Cacheable(cacheNames = "blog",unless = "#result==null")
    @Override
    public Page<Blog> listBlog(Pageable pageable) {
        return blogRepository.findByPublished(pageable);
    }
    @Cacheable(cacheNames = "blog",unless = "#result==null")
    @Override
    public Page<Blog> listBlog(Long tagId, Pageable pageable) {
        return blogRepository.findAll(new Specification<Blog>() {
            @Override
            public Predicate toPredicate(Root<Blog> root, CriteriaQuery<?> cq, CriteriaBuilder cb) {
                Join join =root.join("tags");
                return cb.equal(join.get("id"),tagId) ;
            }
        },pageable);
    }






    //查询
    @Override
    public Page<Blog> listBlog(String query, Pageable pageable) {
        return blogRepository.findByQuery(query,pageable);
    }


    @Cacheable(cacheNames = "blog",unless = "#result==null")
    @Override
    public List<Blog> listRecommendBlogTop(Integer size) {
        Sort sort = Sort.by(Sort.Direction.DESC,"updateTime");
        Pageable pageable = PageRequest.of(0, size, sort);
        return blogRepository.findTop(pageable);
    }
    @Cacheable(cacheNames = "blog",unless = "#result==null")
    @Override
    public Map<String, List<Blog>> archiveBlog() {
        List<String> years = blogRepository.findGroupYear();
        TreeMap<String,List<Blog>> map = new TreeMap<>((o1, o2)->Integer.parseInt(o2)-Integer.parseInt(o1));
        for (String year : years){
            map.put(year,blogRepository.findByYear(year));
        }
        return map;
    }
    @Cacheable(cacheNames = "blog",unless = "#result==null")
    @Override
    public Long countBlog() {
        return blogRepository.count();
    }

    @CachePut(cacheNames = "blog",key = "#result.id")
    @Transactional
    @Override
    public Blog saveBlog(Blog blog) {
        if (blog.getId() == null) {
            blog.setCreateTime(new Date());
            blog.setUpdateTime(new Date());
            blog.setViews(0);
        } else {
            blog.setUpdateTime(new Date());
        }
        return blogRepository.save(blog);
    }
    @CachePut(cacheNames = "blog",key = "#result.id")
    @Transactional
    @Override
    public Blog updateBlog(Long id, Blog blog) {
        Blog b = blogRepository.getOne(id);
        if (b == null) {
            throw new NotFoundException("该博客不存在");
        }
        BeanUtils.copyProperties(blog,b, MyBeanUtils.getNullPropertyNames(blog));
//            BeanUtils.copyProperties(blog,b);
        b.setUpdateTime(new Date());
        return blogRepository.save(b);
    }
    @CacheEvict(cacheNames = "blog")
    @Transactional
    @Override
    public void deleteBlog(Long id) {
        blogRepository.deleteById(id);
    }
}
